/******************************************************************************

    Copyright (C) 2006 Alessio Stalla (alessiostalla@gmail.com)

    This file is part of PrettyProlog.

    PrettyProlog is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    PrettyProlog is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PrettyProlog; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    See the file COPYING for further details.

 *****************************************************************************/

package prettyprolog.engine.syspreds;

import java.util.List;

import prettyprolog.datatypes.Callable;
import prettyprolog.datatypes.Real;
import prettyprolog.datatypes.Substitution;
import prettyprolog.datatypes.Term;
import prettyprolog.engine.Engine;

/**
 * Implements the arg/3 system predicate. arg(N, Fn, T) unifies the nth argument
 * (subterm) of the Callable Fn with T. Thus, N and Fn must be bound to a number
 * and a Callable, respectively, or this predicate will print an error message
 * and fail. Also, if the Callable has not enough arguments, this predicate
 * fails. <br />
 * According to what happens in Sicstus Prolog, argument numbering starts at 1.
 * In Java code, instead, the normal 0-based numbering is used.
 */
public class Arg extends SystemPredicate {

	private static final Arg inst = new Arg();

	private Arg() {
		super(3);
	}

	/** Returns the only instance of this system predicate. */
	public static Arg getInstance() {
		return inst;
	}

	public SyspredEffect doCall(Engine en, Substitution subst, List<Term> args)	throws SyspredException {
		Term n = args.get(0);
		Term fn = args.get(1);
		Term t = args.get(2);
		if ((fn instanceof Callable) && (n instanceof Real)) {
			int narg = (int) ((Real) n).getValue();
			if (((Callable) fn).getArgCount() < narg)
				return new SyspredEffect(true, subst);
			Term arg = ((Callable) fn).getArgs().get(narg - 1);
			Substitution tmp_subst = en.getUnificationAlgorithm().unify(t, arg);
			if (tmp_subst == null) {
				return new SyspredEffect(true, subst);
			}
			return new SyspredEffect(false, subst.compose(tmp_subst));
		} else {
			en.getIOManager().error("arg: not enough arguments are instantiated");
			return new SyspredEffect(true, subst);
		}
	}

	public boolean isBacktrackable() {
		return false;
	}

	public String toString() {
		return super.toString() + " arg/3";
	}
}